//
//  MallHomeChannelToolView.m
//  Yanwei
//
//  Created by 俊杰 on 2018/11/10.
//  Copyright © 2018年 DCloud. All rights reserved.
//

#import "MallHomeChannelToolView.h"
#import "MallHomeMoreChannelView.h"
#import "MallHomeChannelListModel.h"
#import "GoodsModel.h"
#define kLeftMargin 15
#define kPadding 25
#define kRadio 0

@interface MallHomeToolBtn : UIButton
@property (nonatomic, strong) UIView *moveLineView;

@end

@implementation MallHomeToolBtn
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.moveLineView.hidden = YES;
    }
    return self;
}
- (UIView *)moveLineView {
    if (!_moveLineView) {
        _moveLineView = [[UIView alloc] init];
        _moveLineView.backgroundColor = Color175030;
        [self addSubview:_moveLineView];
        [_moveLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.mas_equalTo(3);
        }];
    }
    return _moveLineView;
}
@end

@interface MallHomeChannelToolView()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *toolMoreBtn;
@property (nonatomic, strong) MallHomeToolBtn *seletedBtn;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *bottomLineView;
@property (nonatomic, assign) CGFloat rightMargin;
@end

@implementation MallHomeChannelToolView

- (instancetype)initWithType:(MallHomeChannelToolType)type {
    self = [super init];
    if (self) {
        self.type = type;
        self.rightMargin = type == MallHomeChannelToolLiftType ? 15 : 59;
        self.backgroundColor = [UIColor whiteColor];
        self.toolMoreBtn.hidden = type == MallHomeChannelToolLiftType;
        [self.toolMoreBtn addTarget:self action:@selector(toolMoreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        __weakConfigure
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [__weakSelf.bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(__weakSelf);
                make.height.mas_equalTo(0.5);
            }];
        });
    }
    return self;
}

- (void)setItemArray:(NSArray *)itemArray {
    _itemArray = itemArray;
    [self.scrollView removeAllSubviews]; // 移除所有
    
    NSInteger count = itemArray.count;
    CGFloat titleW = 0;
    CGFloat leftW = 0;
    for (int i = 0; i < count; i++) {
        MallHomeToolBtn *btn = [[MallHomeToolBtn alloc] init];
        btn.tag = i + 1;
        MallHomeChannelListModel *model = itemArray[i];
        NSString *title = model.name;
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitleColor:Color34 forState:UIControlStateNormal];
        if (i == self.currentIndex && self.type == MallHomeChannelToolChannelType) {
            [btn setTitleColor:Color175030 forState:UIControlStateNormal];
            self.seletedBtn = btn;
            self.seletedBtn.moveLineView.hidden = NO;
        }
        btn.titleLabel.font = APPFONT(16);
        [self.scrollView addSubview:btn];
        
        titleW = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : btn.titleLabel.font} context:nil].size.width;
        btn.frame = CGRectMake(kLeftMargin + leftW, 0, titleW, 44);
        leftW = CGRectGetMaxX(btn.frame) + kPadding - kLeftMargin;
        if (i == count - 1) {
            self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(btn.frame), 0);
        }
        [btn addTarget:self action:@selector(chooseBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)setCurrentIndex:(NSInteger)currentIndex {
    _currentIndex = currentIndex;
    if (self.scrollView.subviews.count == 0 ) {
        return;
    }
    [self channelBtnAction:[self.scrollView viewWithTag:currentIndex+1]];
}

- (void)setPosition:(NSInteger)position {
    _position = position;
    for (int i = 0; i < self.itemArray.count; i++) {
        GoodsModel *model = self.itemArray[i];
        if (model.displayLines == position) {
            MallHomeToolBtn *btn = self.scrollView.subviews[i];
            [self channelBtnAction:btn];
            break;
        }
    }
}

#pragma mark - event
- (void)toolMoreBtnAction:(UIButton *)btn {
    btn.selected = !btn.selected;
    self.userInteractionEnabled = NO;
    if (btn.selected) {
        [UIView animateWithDuration:0.25 animations:^{
            btn.imageView.transform = CGAffineTransformMakeRotation(-M_PI);
        } completion:^(BOOL finished) {
//            self.bottomLineView.hidden =
            [self.bottomLineView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self).offset(15);
            }];
            self.titleView.hidden = NO;
            self.userInteractionEnabled = YES;
        }];
        if (self.channelToolArrowBlock) {
            self.channelToolArrowBlock(YES);
        }
    } else {
        [UIView animateWithDuration:0.25 animations:^{
            btn.imageView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self.bottomLineView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self);
            }];
            self.titleView.hidden = YES;
            self.userInteractionEnabled = YES;
        }];
        if (self.channelToolArrowBlock) {
            self.channelToolArrowBlock(NO);
        }
    }
}

- (void)hiddenMoreToolView {
    [self toolMoreBtnAction:self.toolMoreBtn];
}

- (void)chooseBtnAction:(MallHomeToolBtn *)btn {
    if (self.chooseChannelBlock) {
        self.chooseChannelBlock(btn.tag - 1);
    }
    [self channelBtnAction:btn];
}

- (void)channelBtnAction:(MallHomeToolBtn *)btn {
    [self.seletedBtn setTitleColor:Color34 forState:UIControlStateNormal];
    self.seletedBtn.moveLineView.hidden = YES;
    CGFloat x = [btn convertRect:btn.bounds toView:self].origin.x;
    NSInteger tag = btn.tag;
    _currentIndex = tag - 1;
    if ((tag == 1 && x <= (kLeftMargin + kRadio)) || (tag == 2 && x <= (kPadding + kRadio))) {
        [UIView animateWithDuration:0.2 animations:^{
            [self.scrollView setContentOffset:CGPointZero];
        }];
    } else if (x <= (kPadding + kRadio) && tag > 2) {
//        if (tag > self.itemArray.count * 0.5) { // 过半右移
//            [self.scrollView setContentOffset:CGPointMake(btn.right - (ScreenWidth - kMoreWidth), 0) animated:YES];
//            [UIView animateWithDuration:0.2 animations:^{
//                [self.scrollView setContentOffset:CGPointMake(btn.right - (ScreenWidth - kMoreWidth), 0)];
//            }];
//        } else {
            NSInteger preTag = tag - 1;
            UIButton *btn = [self.scrollView viewWithTag:preTag];
            [UIView animateWithDuration:0.2 animations:^{
                [self.scrollView setContentOffset:CGPointMake(btn.left - kPadding, 0)];
            }];
//        }
    } else if ((x + btn.width) >= (ScreenWidth - self.rightMargin - kPadding - kRadio)) {
        if (tag == self.itemArray.count) { // 最后一个
            [UIView animateWithDuration:0.2 animations:^{
                [self.scrollView setContentOffset:CGPointMake(btn.right - (ScreenWidth - self.rightMargin), 0)];
            }];
        } else {
            NSInteger preTag = tag + 1;
            UIButton *btn = [self.scrollView viewWithTag:preTag];
            [UIView animateWithDuration:0.2 animations:^{
                [self.scrollView setContentOffset:CGPointMake(btn.right - (ScreenWidth - self.rightMargin), 0)];
            }];
        }
    }
    self.seletedBtn = btn;
    [self.seletedBtn setTitleColor:Color175030 forState:UIControlStateNormal];
    self.seletedBtn.moveLineView.hidden = self.type != MallHomeChannelToolChannelType;
}

#pragma mark - 懒加载
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        _scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, self.rightMargin);
    }
    return _scrollView;
}

- (UIButton *)toolMoreBtn {
    if (!_toolMoreBtn) {
        _toolMoreBtn = [[UIButton alloc] init];
        [_toolMoreBtn setImage:[UIImage imageNamed:@"mall_home_arrow"] forState:UIControlStateNormal];
        [_toolMoreBtn setBackgroundImage:[UIImage imageNamed:@"mall_home_arrow_bg"] forState:UIControlStateNormal];
        _toolMoreBtn.adjustsImageWhenHighlighted = NO;
        [self insertSubview:_toolMoreBtn aboveSubview:self.scrollView];
        [_toolMoreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.equalTo(self);
            make.width.mas_equalTo(self.rightMargin);
        }];
    }
    return _toolMoreBtn;
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
        _titleView.backgroundColor = RGBACOLOR(250, 250, 250, 1.0);
        [self insertSubview:_titleView belowSubview:_toolMoreBtn];
        [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        
        UILabel *lbl = [[UILabel alloc] init];
        lbl.text = @"全部频道";
        lbl.textColor = Color34;
        lbl.font = APPFONT(16);
        [_titleView addSubview:lbl];
        [lbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.titleView);
            make.left.equalTo(self.titleView).offset(15);
        }];
    }
    return _titleView;
}

- (UIView *)bottomLineView {
    if (!_bottomLineView) {
        _bottomLineView = [[UIView alloc] init];
        _bottomLineView.backgroundColor = Color244;
        [self addSubview:_bottomLineView];
    }
    return _bottomLineView;
}

@end
